package com.kayak.weixin.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.alibaba.dubbo.rpc.RpcException;
import com.kayak.dubbo.bean.ConsumerBean;
import com.kayak.dubbo.bean.RpcBean;
import com.kayak.exception.ErrorException;
import com.kayak.kkutils.JsonUtil;
import com.kayak.kkweb.sys.SysBeans;
import com.kayak.service.msg.weixin.mp.GetMpOauthAccessTokenInterface;
import com.kayak.weixin.pojo.SNSUserInfo;
import com.kayak.weixin.pojo.WeixinOauth2Token;

/**
 * 网页授权工具类
 * @author myt
 *
 */

public class OAuthUtil {
	
	public final static Logger log = LoggerFactory.getLogger(OAuthUtil.class);
	
//	public WeixinOauth2Token getOauth2AccessTokenByMpid(String mpid,String openid) throws ErrorException{
//		ConsumerBean consumerBean = new ConsumerBean();
//		consumerBean.addRequest("mpid", mpid);
//		consumerBean.addRequest("openid", openid);
//		RpcBean rpcBean=null;
//		WeixinOauth2Token weixinOauth2Token = new WeixinOauth2Token();
//		GetMpOauthAccessTokenInterface  getMpOauthAccessTokenService = (GetMpOauthAccessTokenInterface) SysBeans.getBean("getMpOauthAccessTokenService");//获取网页授权access_token
//		try {
//			rpcBean=getMpOauthAccessTokenService.execute(consumerBean);
//			CommonUtil.verifyServiceReturn(rpcBean);
//		} catch (RpcException e) {
//			e.printStackTrace();
//			throw new ErrorException(ErrorCodeWeixin.ERROR_EASYSP_F990_CODE,ErrorCodeWeixin.ERROR_EASYSP_F990_MSG);
//		}
//		if(rpcBean.getResponse("oauth_access_token_json")==null||"".equals(rpcBean.getResponse("oauth_access_token_json"))){
//			return null;
//		}else{
//			Map<String,Object> tokenMap = (Map<String, Object>) JsonUtil.jsonToMap(rpcBean.getResponse("oauth_access_token_json"));
//			weixinOauth2Token.setAccessToken(tokenMap.get("accessToken").toString());
//			weixinOauth2Token.setExpiresIn((int)(Double.parseDouble(tokenMap.get("expiresIn").toString())-200));
//			weixinOauth2Token.setOpenId(tokenMap.get("openId").toString());
//			weixinOauth2Token.setRefreshToken(tokenMap.get("refreshToken").toString());
//			weixinOauth2Token.setScope(tokenMap.get("scope").toString());
//			return weixinOauth2Token;
//		}
//	}
	
	public WeixinOauth2Token getOauth2AccessTokenByMpid(Map<String,Object> tokenMap) throws ErrorException{
		WeixinOauth2Token weixinOauth2Token = new WeixinOauth2Token();
		weixinOauth2Token.setAccessToken(tokenMap.get("accessToken").toString());
		weixinOauth2Token.setExpiresIn((int)(Double.parseDouble(tokenMap.get("expiresIn").toString())-200));
		weixinOauth2Token.setOpenId(tokenMap.get("openId").toString());
		weixinOauth2Token.setRefreshToken(tokenMap.get("refreshToken").toString());
		weixinOauth2Token.setScope(tokenMap.get("scope").toString());
		return weixinOauth2Token;
	}
	/**
	 * 获取网页授权凭证
	 * 
	 * @param appId 公众账号的唯一标识
	 * @param appSecret 公众账号的密钥
	 * @param code
	 * @return WeixinAouth2Token
	 */
	public WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
		WeixinOauth2Token wat = null;
		// 拼接请求地址
		String requestUrl = WeixinConst.OAUTH_ACCESS_TOKEN_URL;
		requestUrl = requestUrl.replace("APPID", appId);
		requestUrl = requestUrl.replace("SECRET", appSecret);
		requestUrl = requestUrl.replace("CODE", code);
		// 获取网页授权凭证
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			try {
				wat = new WeixinOauth2Token();
				wat.setAccessToken(jsonObject.getString("access_token"));
				wat.setExpiresIn(jsonObject.getInt("expires_in"));
				wat.setRefreshToken(jsonObject.getString("refresh_token"));
				wat.setOpenId(jsonObject.getString("openid"));
				wat.setScope(jsonObject.getString("scope"));
			} catch (Exception e) {
				wat = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
			}
		}
		return wat;
	}
	
	/**
	 * 刷新网页授权凭证
	 * 
	 * @param appId 公众账号的唯一标识
	 * @param refreshToken
	 * @return WeixinAouth2Token
	 */
	public WeixinOauth2Token refreshOauth2AccessToken(String appId, String refreshToken) {
		WeixinOauth2Token wat = null;
		// 拼接请求地址
		String requestUrl = WeixinConst.OAUTH_REFRESH_TOKEN_URL;
		requestUrl = requestUrl.replace("APPID", appId);
		requestUrl = requestUrl.replace("REFRESH_TOKEN", refreshToken);
		// 刷新网页授权凭证
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			try {
				wat = new WeixinOauth2Token();
				wat.setAccessToken(jsonObject.getString("access_token"));
				wat.setExpiresIn(jsonObject.getInt("expires_in"));
				wat.setRefreshToken(jsonObject.getString("refresh_token"));
				wat.setOpenId(jsonObject.getString("openid"));
				wat.setScope(jsonObject.getString("scope"));
			} catch (Exception e) {
				wat = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				log.error("刷新网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
			}
		}
		return wat;
	}
	
	/**
	 * 通过网页授权获取用户信息
	 * 
	 * @param accessToken 网页授权接口调用凭证
	 * @param openId 用户标识
	 * @return SNSUserInfo
	 */
	@SuppressWarnings( { "deprecation", "unchecked" })
	public SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
		SNSUserInfo snsUserInfo = null;
		// 拼接请求地址
		String requestUrl = WeixinConst.OAUTH_USERINFO_URL;
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
		// 通过网页授权获取用户信息
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

		if (null != jsonObject) {
			try {
				snsUserInfo = new SNSUserInfo();
				// 用户的标识
				snsUserInfo.setOpenId(jsonObject.getString("openid"));
				// 昵称
				snsUserInfo.setNickname(jsonObject.getString("nickname"));
				// 性别（1是男性，2是女性，0是未知）
				snsUserInfo.setSex(jsonObject.getInt("sex"));
				// 用户所在国家
				snsUserInfo.setCountry(jsonObject.getString("country"));
				// 用户所在省份
				snsUserInfo.setProvince(jsonObject.getString("province"));
				// 用户所在城市
				snsUserInfo.setCity(jsonObject.getString("city"));
				// 用户头像
				snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
				// 用户特权信息
				snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
			} catch (Exception e) {
				snsUserInfo = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
			}
		}
		return snsUserInfo;
	}
	
	/**
	 * 构造网页授权链接
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public String getOAuthUrl(String appid,String url) throws UnsupportedEncodingException{
		String OAuthUrl = WeixinConst.OAUTH_AUTHORIZE_URL;
		OAuthUrl = OAuthUrl.replace("APPID", appid);
		OAuthUrl = OAuthUrl.replace("REDIRECT_URI", URLEncoder.encode(url,"UTF-8"));
		OAuthUrl = OAuthUrl.replace("SCOPE", "snsapi_userinfo");
		return OAuthUrl;
	}
}
